package com.lagou.rabbitmqdemo.controller;

import com.lagou.rabbitmqdemo.db.OrderDB;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.transform.Source;
import java.util.Map;
import java.util.UUID;

@RestController
public class GoController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/createOrder/{userId}")
    public String createOrder(@PathVariable String userId) {
        String s = UUID.randomUUID().toString();

        // 生成订单编号
        String orderNo = userId + s;
        OrderDB.add(userId, orderNo);

        // 将订单放入延迟队列
        rabbitTemplate.convertAndSend("ex.go", "go", orderNo);
        return "订单已生成，编号为" + orderNo + "，请在2分钟内支付！";
    }

    @RequestMapping("/doPay/{userId}/{orderNo}")
    public String doPay(@PathVariable String userId, @PathVariable String orderNo) {
        boolean isExpire = OrderDB.checkExpire(orderNo);

        String result = "";
        if (isExpire) {
            result = "订单已过期<pre></pre>" + getOrderList(userId);

        } else {
            OrderDB.complete(orderNo);
            result = "订单 " + orderNo + "支付完成";
        }

        return result;
    }

    @RequestMapping("/getOrderList/{userId}")
    public String getOrderList(@PathVariable String userId) {
        Map<String, String> orderList = OrderDB.getOrderList(userId);

        if (orderList == null) return "无订单信息";

        StringBuffer result = new StringBuffer("订单信息：<pre></pre>");
        orderList.entrySet().forEach(e -> {
            String key = e.getKey();
            String value = e.getValue();
            System.out.println(key + ":" + value);
            result.append("订单编号 " + key + "," + OrderDB.state.get(value) + "<pre></pre>");
        });

        return result.toString();
    }
}
